<template>
  <div class="login">
    <div class="title-container">
      <h3 class="title">OJ系统 管理员登录</h3>
    </div>
    <div class="login-form-container">
      <img src="../assets/极课堂logo.png" style="margin: 40px 192px 10px 192px; width: 136px; height: 33px">


      <el-form ref="loginForm2" :rules="loginFormRules" :model="loginForm" class="login-form">
        <el-form-item prop="phone">
          <el-input v-model="loginForm.phone" placeholder="请输入手机号">
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input type="password" v-model="loginForm.password"  placeholder="请输入密码">
          </el-input>
        </el-form-item>
        <el-row>
          <el-button class="login-button1" @click="loginSubmit()">登录</el-button>
        </el-row>
      </el-form>




  <el-dialog v-model="firstLogin" title="首次登陆请修改密码" width="500" >
    <el-form :model="registerBind" :rules="userInfoFormRules">
      <el-form-item :label-width="formLabelWidth" prop="username">
        <el-input v-model="registerBind.username" autocomplete="off" placeholder="请输入用户名"/>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth" prop="mobile">
        <el-input v-model="registerBind.phone" autocomplete="off" placeholder="请输入手机号"/>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth" prop="password">
        <el-input v-model="registerBind.password" autocomplete="off" placeholder="请输入密码"/>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth">
        <div class="codeDiv">
          <el-input class="registerCode" v-model="registerBind.code" autocomplete="off" placeholder="请输入验证码"/>
          <el-button class="getRegisterCode" @click="getCode">获取验证码</el-button>
        </div>
      </el-form-item>
      <div class="dialog-footer">
        <el-button type="primary" @click="registerPhone">
          激活
        </el-button>
      </div>
      <!--        滑块验证-->
      <div >
        <Vcode :show="isShow" @success="success" @close="close" @fail='fail' ></Vcode>
      </div>
    </el-form>

  </el-dialog>
    </div>
  </div>
</template>
<script setup>
import {reactive, ref} from 'vue'
import {useStore} from 'vuex'
import {useRouter} from 'vue-router'
import axios from 'axios'
import {JSEncrypt} from "jsencrypt";
import { ElMessage } from 'element-plus'
import  API from '@/api/manage'
import Vcode from "vue3-puzzle-vcode";
const close=()=>{
  isShow.value=false
}
const fail=()=>{
  ElMessage.error('验证失败')
}
let firstLogin = ref(false)

let registerBind = reactive({

  username: null,
  code: null,
  phone: null,
  random: null,
  password: null

})
let userInfoFormRules = reactive({
  username: [
    {required: true, message: "请输入用户名", trigger: "blur"}
  ],
  realname: [{required: true, message: "请输入姓名", trigger: "blur"}],
  password: [{required: true, message: "请输入密码", trigger: "blur"}],
  mobile: [
    {
      required: true,
      validator: function (rule, value, callback) {
        const regMobile =/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
        if (registerBind.phone === null) {
          callback(new Error("请输入手机号码"));
        } else if (!regMobile.test(registerBind.phone)) {
          console.log(registerBind.phone)
          callback(new Error("输入的手机号码格式错误"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  email: [
    {
      required: true,
      message: "请输入邮箱",
      trigger: "blur"
    },
    {
      validator: function (rule, value, callback) {
        if (
            /^\w{1,64}@[a-z0-9\-]{1,256}(\.[a-z]{2,6}){1,2}$/i.test(
                value
            ) == false
        ) {
          callback(new Error("邮箱格式错误"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
})
const loginForm = reactive({
  username: '',
  code: '',
  phone: '',
  password:'',
  random:'',
  role:'1',
  identify:1
})
let registerForm=reactive({
  username:'',
  phone:'',
  realName:'',
  sex:1,
  code:'',
  random:'',
  type:2
})
let registerSubmitForm=reactive({
  username:'',
  phone:'',
  realName:'',
  sex:1,
  code:'',
  random:'',
  type:2
})

const store=useStore()

const success=()=>{
  isShow.value=false
  API.getPublic().then((res)=>{
    if(res.data.code==='0'){
      // 使用jsencrypt加密
      entry.setPublicKey(res.data.content.publicKeyStr)
      registerSubmitForm.username =  entry.encrypt(registerBind.username)
      registerSubmitForm.phone=entry.encrypt(registerBind.phone)
      registerSubmitForm.random=res.data.content.random
      random=res.data.content.random
      API.getPhoneCode(registerSubmitForm).then((res)=>{
        if(res.data.code==='0'){
          ElMessage.success('验证码已发送')
        }
      }).catch(error=>{
        console.log(error)
      })
    }
  }).catch(error=>{
    console.log(error)
  })
}


let isShow=ref(false)

const dialogVisible = ref(false)
const exitRegister=()=>{
  dialogVisible.value=false
  registerForm={
    username:'',
    phone:'',
    realName:'',
    sex:1
  }
}

let random=ref()



const entry = new JSEncrypt()
// 激活修改密码
const registerPhone = () => {
          // 使用jsencrypt加密
          registerBind.username = entry.encrypt(registerBind.username)
          registerBind.password =  entry.encrypt(registerBind.password)
          registerBind.phone=  entry.encrypt(registerBind.phone)
          registerBind.code=  entry.encrypt(registerBind.code)
          registerBind.random =random
          axios.post("http://localhost:8080/login/adminAcativity", registerBind).then((res) => {
            if (res.data.success === true) {
              ElMessage.success('激活成功,请重新登录！')
              registerBind=reactive({})
              firstLogin.value=false
              location.reload();
            } else {

            }
          })
}

// 点击获取验证码
const getCode=()=>{
  if(!registerBind.username){
    ElMessage.error('请输入用户名')
  }
  else if(!registerBind.phone){
    ElMessage.error('请输入手机号')
  }
  else if(!registerBind.password){
    ElMessage.error('请输入新密码')
  }
  else{
    isShow.value=true
  }
}
const loginFormRules = reactive({
  username: [
    {required: true, message: '账户不可为空', trigger: 'blur'},
    {max: 20, message: '长度在 20 个字符以内', trigger: 'change'}
  ],

})
const router = useRouter()

let param = reactive({})


const loginSubmit = () => {
  param.type = 2
  param.loginStatus = '2'

    API.getPublic().then((res) => {
      if (res.data.code === '0') {
        // 使用jsencrypt加密
        const entry = new JSEncrypt()
        entry.setPublicKey(res.data.content.publicKeyStr)
        param.phone =  entry.encrypt(loginForm.phone)
        param.password = entry.encrypt(loginForm.password)
        param.random=res.data.content.random
        API.userLogin(param).then((result)=>{
          if(result.data.success) {
            if (result.data.content.status === "1") {
              firstLogin.value = true
            } else {
              localStorage.setItem('token', result.data.content.token)
              let token=localStorage.getItem('token')
              API.userList({
                size:1,
                current:1,
                phone:loginForm.phone
              },token).then(res1=>{
                console.log(res1,'res111')
                if(res1.data.success===true){
                  if(res1.data.content.records[0].identify===1){
                    store.commit('user/logined')
                    store.commit('user/setIdentify',1)
                    router.push({path: '/public'})

                    ElMessage.success('登录成功')
                  }
                  else if(res1.data.content.records[0].identify===2){
                    API.queryUserRole({
                      id:res1.data.content.records[0].role
                    },token).then(res2=>{
                      if(res2.data.success===true){
                        localStorage.setItem('cid',res2.data.content.records[0].cid)
                        store.commit('user/logined')
                        store.commit('user/setIdentify',2)
                        router.push({path: '/publicnew'})
                        ElMessage.success('登录成功')
                      }
                    }).catch(err=>{
                      console.log(err)
                    })
                  }
                  else{
                    ElMessage.error('身份错误！当前为管理员端')
                  }
                }
              }).catch(err1=>{
                console.log(err1)
              })
            }
          }
        }).catch(res=>{
          ElMessage.error(res.response.data.message)
        })
      }
    }).catch(error=>{
      console.log(error)
    })
}
</script>

<style scoped>

.login {
  position: fixed;
  height: 100%;
  width: 100%;
  background: url("../assets/bg-login.png") no-repeat center;
  background-size: 100% 100%;
  color: white;
}

.login-form-container {
  position: absolute;
  left: 60%;
  top: 28%;
  width: 520px;
  height: 400px;
  background-color: #D1FCF4;
  border-radius: 2%;
}

.login-form {
  position: absolute;
  left: 0;
  right: 0;
  width: 450px;
  padding: 0px 35px 10px 35px;
  margin: 15px auto;
}

.title-container .title {
  font-size: 50px;
  color: #eee;
  margin: 7% auto 40px auto;
  text-align: center;
  font-family: Serif;
}

.login .el-form-item {
  border: 1px solid rgba(255, 255, 255, 0.1);
  /* background: rgba(133, 129, 129, 0.1); */
  border-radius: 5px;
  /* color: #454545; */
  width: 320px;
  height: 60px;
  margin: 0px auto 10px auto;
}

.el-form-item .prep-icon-span {
  font-size: 20px;
}

.el-button {
  display: block;
  width: 320px;
  margin: 25px auto;
  background-image: linear-gradient(#81E6D4, #16AF93);
  border-radius: 10px;
  font-size: 20px;
  font-weight: bold;
}
.el-button.login-button{
  background:white;
  width: 120px;
  border: 1px solid;
  background-color: transparent;
  text-transform: uppercase;
  font-size: 15px;
  padding: 10px 20px;
  font-weight: 400;
}
.el-button.login-button1{
  background:white;
  width: 80px;
  border: 0.5px solid;
  text-transform: uppercase;
  font-size: 15px;
  padding: 10px 20px;
  font-weight: 400;
}

a {
  font-size: 13px;
  color: black;
  cursor: pointer;
  text-decoration: none;
  margin-left: 20px;
}
.codeDiv {
  width: 100%;
  display: flex;
}

.registerCode {
  margin-top: 28px;
  margin-right: 10px;
  height: 50%;
  flex-grow: 3; /* 占据四分之三宽度 */

}

.getRegisterCode {

  flex-grow: 1; /* 占据四分之一宽度 */
}

</style>
